/*
 * @Description: 封装路由
 * @version:
 * @Author: m
 * @LastEditors: m
 */
import Vue from "vue";
import Router from "vue-router";
import { getToken } from "@/utils/auth";
import getPageTitle from "@/utils/get-page-title";

const whiteList = ["/login"];

var router = new Router({
	// mode: 'history',
	base: "/",
	routes: [
		{
			path: "/",
			name: "home",
			component: () => import("@/views/home/index"),
			meta: { title: "主页", keepAlive: true, auth: true },
		},

		{
			path: "/login",
			name: "login",
			component: () => import("@/views/login/index"),
			meta: { title: "登录", keepAlive: true, auth: true },
		},
	],
});

router.beforeEach(async (to, from, next) => {
	document.title = getPageTitle(to.meta.title);

	const hasToken = getToken();

	next();

	if (!to.name) {
		next("/");
	}

	// 路由守卫 如果token为空,跳转登录
	if (to.meta.auth) {
		if (hasToken == "undefined" || hasToken == undefined || hasToken == "") {
			if (whiteList.indexOf(to.path) !== -1) {
				next();
			} else if (to.path === "/error") {
				next();
			} else {
				next({
					path: "/login",
					query: {
						link: to.name,
					},
				});
			}
		} else {
			if (to.path === "/login") {
				next({ path: "/" });
			}
			next();
		}
	} else {
		next();
	}
});

export default router;

Vue.use(Router);
